import { Inject, Injectable } from '@nestjs/common';
import { RedisClientType } from '@redis/client';

type HashValue = string | number;
type HashObject = Record<string, HashValue>;

@Injectable()
export class RedisService {
  constructor(
    @Inject('REDIS_SERVICE') private readonly redisClient: RedisClientType,
  ) {}

  async get(key: string) {
    return await this.redisClient.get(key);
  }

  async set(key: string, value: string, expireTime?: number) {
    await this.redisClient.set(key, value);
    if (expireTime) {
      await this.redisClient.expire(key, expireTime);
    }
  }

  async hashGet(key: string): Promise<HashObject> {
    return await this.redisClient.hGetAll(key);
  }

  async hashSet(key: string, value: Record<string, any>, expireTime?: number) {
    for (const [k, v] of Object.entries(value)) {
      await this.redisClient.hSet(key, k, v);
    }

    if (expireTime) {
      await this.redisClient.expire(key, expireTime);
    }
  }

  async getKeys(pattern: string) {
    return await this.redisClient.keys(pattern);
  }
}
